package com.sita.linboard.calllist;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.hyphenate.EMCallBack;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMCmdMessageBody;
import com.hyphenate.chat.EMMessage;
import com.sita.linboard.R;
import com.sita.linboard.base.ActivityCollector;
import com.sita.linboard.base.BaseActivity;
import com.sita.linboard.base.BaseApplication;
import com.sita.linboard.http.RestClient;
import com.sita.linboard.journey.OrderReceivActivity;
import com.sita.linboard.utils.RestResponse;
import com.sita.linboard.utils.SpUtils;
import com.sita.linboard.utils.ToastUtils;

import java.sql.Time;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response;

/**
 * Created by Jason on 2016/8/24.
 */
public class VehicleListAdapter extends RecyclerView.Adapter<VehicleListAdapter.MyViewHolder>{
  private Context context;
    private VehicleListBackBean data;


    public VehicleListAdapter(Context contexts) {
        this.context = contexts;
        data  = new VehicleListBackBean();
    }
    public void getData(VehicleListBackBean backBean, ProgressBar bar){

        data = backBean;
        notifyDataSetChanged();
        if (bar!=null){
            bar.setVisibility(View.GONE);
        }

    }

    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        MyViewHolder holder = new MyViewHolder(LayoutInflater.from(context).
                inflate(R.layout.item_callvehicle, parent,
                false));
        return holder;
    }

    @Override
    public void onBindViewHolder(MyViewHolder holder, int position) {
        holder.start_Tx.setText(context.getString(R.string.start_location,data.getData().get(position).getDeparture_addr()));
        holder.end_Tx.setText(context.getString(R.string.end_location,data.getData().get(position).getArrival_addr()));
        holder.positions = position;
        Calendar c = Calendar.getInstance();
        int minute = c.get(Calendar.MINUTE);
        int hour = c.get(Calendar.HOUR_OF_DAY);


       int year = c.get(Calendar.YEAR);
        int month = c.get(Calendar.MONTH);
        int  day = c.get(Calendar.DAY_OF_MONTH);

        int hourvalue =hour-Integer.parseInt(data.getData().get(position).getCreate_time().substring(11,13));
        int minutevalue = minute-Integer.parseInt(data.getData().get(position).getCreate_time().substring(14,16));
        if (String.valueOf(day).equals(data.getData().get(position).getCreate_time().substring(8,10)))
        {
            Log.e("000000", String.valueOf(day).toString());
            if (hourvalue > 0) {
                holder.OtderTime.setText(hourvalue + "小时前");
            } else if (hourvalue == 0) {
//                if (minutevalue > 30) {
//                    holder.OtderTime.setText("30" + "分钟前");
//                } else if (minutevalue <= 30 && minutevalue > 10) {
//                    holder.OtderTime.setText("10" + "分钟前");
//                } else if (minutevalue >= 1 && minutevalue <= 10) {
//                    holder.OtderTime.setText(minutevalue + "分钟前");
//                } else if (minutevalue == 0) {
//                    holder.OtderTime.setText("1" + "分钟内");
//                }
                if(minutevalue == 0) {
                    holder.OtderTime.setText("1" + "分钟内");
                }else {
                    holder.OtderTime.setText(minutevalue + "分钟前");
                }
            }

            else {
                holder.OtderTime.setText("无效订单");
            }
        }

    }

    @Override
    public int getItemCount() {
        if (data.getData() ==null){
            return 0;
        }
        else {
            return data.getData().size();
        }
    }

    class MyViewHolder extends RecyclerView.ViewHolder{
        TextView start_Tx,end_Tx,OtderTime;
        Button order;
        int positions;
        Button call_img;


        public MyViewHolder(View itemView) {
            super(itemView);
            call_img = (Button) itemView.findViewById(R.id.call_user);
            start_Tx = (TextView) itemView.findViewById(R.id.start_location);
            end_Tx = (TextView) itemView.findViewById(R.id.end_location);
            order = (Button) itemView.findViewById(R.id.order_btn);
            OtderTime = (TextView) itemView.findViewById(R.id.order_time);
            call_img.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    BaseActivity.callToUser(context);
                }
            });
            order.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (BaseApplication.isNetworkAvailable()) {


                        final VehicleListBackBean.DataBean bean = data.getData().get(positions);

                        GetOrderRequest request = new GetOrderRequest();

                        request.driver_id = SpUtils.getString("AccoundID", null, BaseApplication.getContext());

                        request.trip_id = bean.getTrip_id();

                        RestClient.getRestService().getOrder(request, new Callback<VehicleListBackBean>() {
                            @Override
                            public void success(VehicleListBackBean getOrderBackBean, Response response) {

                                if (getOrderBackBean.getErrorCode().equals("0") || getOrderBackBean.getData().get(0) != null) {

                                    if (getOrderBackBean.getData().get(0).getState() == 1) {
                                        //成功之后给发送透传
                                        //由服务端发
                                        // sendCMDMessage(bean);
                                        data.getData().remove(positions);

                                        UtilsBean utilsBean = new UtilsBean();
                                        utilsBean.setArrival_addr(getOrderBackBean.getData().get(0).getArrival_addr());
                                        utilsBean.setArrival_lat(getOrderBackBean.getData().get(0).getArrival_lat());
                                        utilsBean.setArrival_lng(getOrderBackBean.getData().get(0).getArrival_lng());
                                        utilsBean.setCustomer_id(getOrderBackBean.getData().get(0).getCustomer().getAccountId());
                                        utilsBean.setDeparture_addr(getOrderBackBean.getData().get(0).getDeparture_addr());
                                        utilsBean.setDeparture_lng(getOrderBackBean.getData().get(0).getDeparture_lng());
                                        utilsBean.setDeparture_lat(getOrderBackBean.getData().get(0).getDeparture_lat());
                                        utilsBean.setTrip_id(getOrderBackBean.getData().get(0).getTrip_id());
                                        OrderReceivActivity.OrderIntent(context, utilsBean, "0");
                                        SpUtils.putString("trip_id", getOrderBackBean.getData().get(0).getTrip_id(), BaseApplication.getContext());
                                        SpUtils.putString("user_poone",getOrderBackBean.getData().get(0).getCustomer().getMobile(),BaseApplication.getContext());
                                        notifyDataSetChanged();
                                    } else {

                                        getData(getOrderBackBean,null);
                                        //   Log.e("订单失败");
                                    }
                                }
                            }
                            @Override
                            public void failure(RetrofitError error) {
                                Log.e("ss", error.toString());
                            }
                        });
                    }
                    else {
                        ToastUtils.show("网络异常",3);
                    }
                }

            });

        }


    }
    private void sendCMDMessage(VehicleListBackBean.DataBean bean){
        //点击接单以后发送透传消息给用户。
        EMMessage cmdMsg = EMMessage.createSendMessage(EMMessage.Type.CMD);
       // String action = "THEORDER";
        EMCmdMessageBody cmdBody = new EMCmdMessageBody("THEORDER");
        cmdMsg.setReceipt(String.valueOf(bean.getCustomer().getAccountId()));

        cmdMsg.setAttribute("action","THEORDER");
        cmdMsg.setAttribute("driverID",SpUtils.getString("AccoundID",null,BaseApplication.getContext()));
        cmdMsg.setAttribute("state","已接单");
        cmdMsg.setAttribute("driver_phone",SpUtils.getString("mobile",null,BaseApplication.getContext()));
        cmdMsg.addBody(cmdBody);
        EMClient.getInstance().chatManager().sendMessage(cmdMsg);
        cmdMsg.setMessageStatusCallback(new EMCallBack() {
                @Override
                public void onSuccess() {
                    Log.d("VehicleList", "send share location success");
                }

                @Override
                public void onError(int i, String s) {
                }

                @Override
                public void onProgress(int i, String s) {

                }
        });
    }

}
